package main.old.new_2023.last.month_6;

import java.util.*;

/**
 * @Description:
 * //TODO 剑指 Offer06. 从尾到头打印链表
 * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 *
 * //todo 剑指 Offer 24. 反转链表
 * 定义一个函数，输入一个链表的头节点，反转该链表并输出反转后链表的头节点。
 * @Author: Take-off
 * @Date: 1:00 PM 2023/6/5
 * @Param:
 * @return:
 **/
public class Solution0608 {

    //从尾到头打印链表
    public int[] reversePrint(ListNode head) {

        Stack<ListNode> stack = new Stack<ListNode>();
        ListNode temp = head;
        while (temp != null) {
            stack.push(temp);
            temp = temp.next;
        }
        int size = stack.size();
        int[] print = new int[size];
        for (int i = 0; i < size; i++) {
            print[i] = stack.pop().val;
        }
        return print;

    }

    //反转链表
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    public static class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
    }

    public static void main(String[] args) {
        ListNode  a= new ListNode(1);
        ListNode  b= new ListNode(2);
        ListNode  c= new ListNode(3);
        ListNode  d= new ListNode(4);
        ListNode  e= new ListNode(5);
        a.next = b;
        b.next = c;
        c.next = d;
        d.next = e;

        Solution0608 solu = new Solution0608();
        ListNode listNode = solu.reverseList(a);
        System.out.println(listNode);
    }

}
